﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ImageStationNumAdapt
{
    public partial class ImgStationNumAdapt : Form
    {

        List<string> filenames = new List<string>();
        List<FileInfo> fileNameList = new List<FileInfo>();
        public ImgStationNumAdapt()
        {
            InitializeComponent();
        }

        private void ImgStationNumAdapt_Load(object sender, EventArgs e)
        {
            string input = "K100+000-K100+002_1.jpg";
            string pattern = @"\d+"; // 匹配一个或多个连续数字

            MatchCollection matches = Regex.Matches(input, pattern);

            double[] numbers = matches.Cast<Match>()
                              .Select(m => double.Parse(m.Value))
                              .ToArray();
            // 遍历所有匹配并输出
            foreach (Match match in matches)
            {
                Console.WriteLine(match.Value);
            }
        }

        private string _lastSelectedPath;
        private void btn_ChoosePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            // 如果之前有选择过路径，则设置为对话框的初始路径
            if (!string.IsNullOrEmpty(_lastSelectedPath))
            {
                folderBrowserDialog.SelectedPath = _lastSelectedPath;
            }
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                _lastSelectedPath = folderBrowserDialog.SelectedPath;
                txt_ImgPath.Text = folderBrowserDialog.SelectedPath;
                Reload();
            };
        }

        /// <summary>
        /// 
        /// </summary>
        private async void Reload()
        {
            // 清空文本框，提示用户正在加载
            txt_OldNames.Text = "加载中...";
            var result = await Task.Run(() =>
            {

                System.IO.DirectoryInfo folder = new DirectoryInfo($"{txt_ImgPath.Text}\\CrackSavePicture\\Conconat");
                var list = folder.GetFiles();
                var name = Path.GetFileNameWithoutExtension(list[0].FullName);
                string pattern = @"\d+"; // 匹配一个或多个连续数字
                var extent = Path.GetExtension(list[0].FullName);
                MatchCollection matches = Regex.Matches(name, pattern);

                double[] numbers = matches.Cast<Match>()
                                  .Select(m => double.Parse(m.Value))
                                  .ToArray();
                var direction = 1;

                if ((numbers[0] * 1000 + numbers[1]) < (numbers[2] * 1000 + numbers[3]))
                {
                    direction = 1; // 上行
                    fileNameList = list.ToList().OrderBy(s => s.Name, new FileComparer()).ToList();
                }
                else
                {
                    direction = 2;//下行
                    fileNameList = list.ToList().OrderByDescending(s => s.Name, new FileComparer()).ToList();
                }
                // 使用 StringBuilder 高效构建字符串
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < fileNameList.Count; i++)
                {
                    sb.AppendLine(fileNameList[i].Name);
                }
                return sb.ToString();

            });

            txt_OldNames.Text = result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Sure_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                if (fileNameList.Count != filenames.Count)
                {
                    MessageBox.Show("请先点击【桩号预览】按钮，确认无误之后再点击【确定处理】按钮 ");
                    return;
                }
                for (int i = 0; i < fileNameList.Count; i++)
                {
                    var path = Path.GetDirectoryName(fileNameList[i].FullName);
                    var newFile = $"{path}\\{filenames[i]}";
                    if (!File.Exists(newFile))
                    {
                        File.Move(fileNameList[i].FullName, $"{path}\\{filenames[i]}");
                    }

                    this.Invoke(new Action(() =>
                    {
                        progressBar1.Value = (i + 1) / fileNameList.Count * 100;
                    }));
                }
                this.Invoke(new Action(() =>
                {
                    Reload();
                }));
            });
        }


        public class FileComparer : IComparer<string>
        {
            [System.Runtime.InteropServices.DllImport("Shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
            public static extern int StrCmpLogicalW(string psz1, string psz2);
            public int Compare(string psz1, string psz2)
            {
                return StrCmpLogicalW(psz1, psz2);
            }
        }

        private void btn_PreView_Click(object sender, EventArgs e)
        {
            textBox3.Text = "加载中...";
            filenames.Clear();
            if (double.TryParse(txt_DistancePro.Text, out double distance))
            {
                System.IO.DirectoryInfo folder = new DirectoryInfo($"{txt_ImgPath.Text}\\CrackSavePicture\\Conconat");
                if (!folder.Exists)
                {
                    MessageBox.Show("请先点击【选择文件夹】按钮");
                    return;
                }
                var list = folder.GetFiles();
                var name = Path.GetFileNameWithoutExtension(list.FirstOrDefault().FullName);
                string pattern = @"\d+"; // 匹配一个或多个连续数字
                var extent = Path.GetExtension(list.FirstOrDefault().FullName);
                MatchCollection matches = Regex.Matches(name, pattern);

                double[] numbers = matches.Cast<Match>()
                                  .Select(m => double.Parse(m.Value))
                                  .ToArray();
                var direction = 1;

                if ((numbers[0] * 1000 + numbers[1]) < (numbers[2] * 1000 + numbers[3]))
                {
                    direction = 1; // 上行
                    fileNameList = list.ToList().OrderBy(s => s.Name, new FileComparer()).ToList();
                }
                else
                {
                    direction = 2;//下行
                    fileNameList = list.ToList().OrderByDescending(s => s.Name, new FileComparer()).ToList();
                }
                matches = Regex.Matches(fileNameList.FirstOrDefault().Name, pattern);
                numbers = matches.Cast<Match>()
                              .Select(m => double.Parse(m.Value))
                              .ToArray(); ;

                double startKm = numbers[0];
                double startM = numbers[1];
                double endKm = numbers[2];
                double endM = numbers[3];
                double startDis = startKm * 1000000 + startM * 1000;
                double endDis = 0;
                for (int i = 0; i < list.Length; i++)
                {
                    if (direction == 1)
                    {
                        startKm = (int)startDis / 1000000;
                        startM = Math.Round(startDis % 1000000, 0) / 1000;
                        endDis = startDis + distance * 1000;
                        endKm = (int)endDis / 1000000;
                        endM = Math.Round(endDis % 1000000, 0) / 1000;
                        startDis = endDis;
                    }
                    else
                    {
                        startKm = (int)startDis / 1000000;
                        startM = Math.Round(startDis % 1000000, 0) / 1000;
                        endDis = startDis - distance * 1000;
                        endKm = (int)endDis / 1000000;
                        endM = Math.Round(endDis % 1000000, 0) / 1000;
                        startDis = endDis;
                    }

                    var stationNum = $"K{startKm}+{startM.ToString("000")}-K{endKm}+{endM.ToString("000")}_1{extent}";
                    filenames.Add(stationNum);
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < filenames.Count; i++)
                {
                    sb.AppendLine(filenames[i]);
                }
                textBox3.Text = sb.ToString();
            }
        }
    }
}
